// pages/ticket/car_ticket.js
var app = getApp();
var Util= require('../../utils/util.js')
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
var STATION_FIRST_INDEX = 100;
var _mapDraw = require("../../lib/mapDraw.js");
var _uplus = require("../../lib/uplus.js");

var actions = {
  drawLine: function drawLine(isClick) {
      var _this4 = this;
      var pointList = this.data.pointList;
      var stationList = this.data.busStop;
      this.markerList.clear();
      this.polylineList.clear();
      var includePoints = [];
      //根据stationList 设置markers
              stationList.forEach(function(item, index, array) {
          var markerId = STATION_FIRST_INDEX + index;
          if (item.stationTag) {
              item.isTempStation = true;
              // item.stationName = item.stationName.replace(/临时停靠点/, "");
                      } else {
              item.isTempStation = false;
          }
          var currentMarker = void 0;
          if (item.type == 0) {
              currentMarker = new _mapDraw.Marker(new _uplus.Point(item.lng, item.lat), "udianbusStartStationPos", {
                  isFirstOrLast: index === 0 || index === array.length - 1,
                  isSelected: item.id === _this4.data.startStationId || item.id === _this4.data.endStationId
              });
          } else {
              currentMarker = new _mapDraw.Marker(new _uplus.Point(item.lng, item.lat), "udianbusEndStationPos", {
                  isStart: item.id === _this4.data.startStationId,
                  isSelected: item.id === _this4.data.startStationId || item.id === _this4.data.endStationId
              });
          }
          if (item.id === _this4.data.currentStopId) {
              // currentMarker.setCallout({
              //   content: item.stopName,
              //   display: "ALWAYS"
              // })
              currentMarker.setLabel({
                  content: item.name,
                  color: "#1B1B1B",
                  fontSize: 12,
                  anchorX: -25,
                  anchorY: 8,
                  padding: 1,
                  textAlign: "center"
              });
          }
          _this4.markerList.addMarker(currentMarker, false, markerId);
          if (isClick) {
            if (item.id === _this4.data.currentStopId) {
              includePoints.push({
                  longitude: item.lng,
                  latitude: item.lat
              });
          }
          } else {
              includePoints.push({
                  longitude: item.lng,
                  latitude: item.lat
              });
          }

      });
    
      console.log(includePoints)
      this.polylineList.addPolyline(new _mapDraw.Polyline(pointList, "dingzhibus"));
      this.setData({
          polyline: this.polylineList.getPolylines(),
          markers: this.markerList.getMarkers(),
          includePoints: includePoints
      });
  }
};

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isRegular: 0,
    bus_line_id:'',
    defaultRegular: [],
    isMid: true,
    busStop: [],
    regular:[],
    defaultMarkers: [],
    latitude: 26.618682,
    longitude: 106.674463,
    polyline: [],
    scaleControl: true,
    parameter: {
      'navbar': '1',
      'return': '1',
      'title': '线路详情',
      'color': false,
    },

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ 
      isRegular: options.is_regular,
      busLineId: options.id,

    });
    wx.setNavigationBarTitle({
      title: '线路详情'  //修改title
    })
   // 页面初始化 options为页面跳转所带来的参数
   this.getDefaultRegular(options.id);
   this.getBusStop(options.id);

   this.markerList = new _mapDraw.MarkerList();
   this.polylineList = new _mapDraw.PolylineList();

   // 实例化API核心类
  //  qqmapsdk = new QQMapWX({
  //   key: 'BL4BZ-Y2YR4-CIBUR-DZ7SH-PXYBQ-42BU4'
  // });
  
  },
  showMid:function(){
    var that = this
    this.setData({
      isMid: !that.data.isMid,
    })
  },
  goHere: function goHere(e) {
    var obj = e.currentTarget.dataset.obj;
    wx.openLocation({
        //​使用微信内置地图查看位置。
        latitude: Number(obj.lat),
        longitude: Number(obj.lng),
        name: obj.name
    });
},
  radio: function (e) {
    var index = e.currentTarget.dataset.index;//获取当前点击的下标
    var defaultRegular = this.data.defaultRegular;//选项集合
    if (defaultRegular[index].checked) return;//如果点击的当前已选中则返回
    defaultRegular.forEach(item => {
      item.checked = false
    })
    defaultRegular[index].checked = true;//改变当前选中的checked值
    this.setData({
      defaultRegular: defaultRegular
    });
  },
  radioChange: function (e) {
    var checkValue = e.detail.value;
    this.setData({
      checkValue: checkValue,
      regular: this.data.defaultRegular[checkValue],
    });
    console.log(this.data.regular)
  },
  getBusStop:function(id){
    var _this1 = this;
    var url = app.U({ c: 'public_api', a: 'get_bus_stop' ,q:{id:id}}, app.globalData.url);
    app.baseGet(url,function(res){  
      if(res.data[0].length){
      var data = res.data
      _this1.setData({
        busStop: data[0],
        pointList: data[1],
        startStationId: data[0][0].id || "",
        endStationId: data[0][data[0].length-1].id || "",
      })
    }else{
      _this1.setData({
        busStop:[],
        pointList: [],
        startStationId: "",
        endStationId:  "",
      })
    }
      actions.drawLine.call(_this1);
    });
  },
  getDefaultRegular:function(id){
    var that = this;
    var url = app.U({ c: 'public_api', a: 'get_default_regular' ,q:{id:id}}, app.globalData.url);
    app.baseGet(url,function(res){  
      if(res.data.length){
      res.data[0].checked = true; 
      that.setData({
        defaultRegular: res.data,
        regular: res.data[0]
      })
    }
    });
  },
  onStationTap: function onStationTap(e) {
    var _this8 = this;
    var target = e.currentTarget;
    var currentStopId = target.dataset.stopid;
    var currentStopType = target.dataset.stoptype;
    this.setData({
        currentStopId: currentStopId
    }, function() {
        actions.drawLine.call(_this8, true);
    });
},
  //点击地图站点
  onMarkerTap: function onMarkerTap(e) {
    var _this9 = this;
    var markerId = e.markerId;
    var currentStopId = this.data.busStop[markerId - STATION_FIRST_INDEX].id;
    this.setData({
        currentStopId: currentStopId
    }, function() {
        actions.drawLine.call(_this9, true);
    });
},
   //地图视野发生变化时触发
   onRegionChange: function onRegionChange(e) {
    var _this11 = this;
    if (e.type == "end" && e.causedBy == "scale") {
        // console.log(this.data.mapScale)
        var mapContext = wx.createMapContext("theMap", this);
        mapContext.getScale({
            complete: function complete(e) {
                if (e.scale && e.scale <= 6) {
                    _this11.setData({
                        scaleControl: false
                    });
                } else {
                    _this11.setData({
                        scaleControl: true
                    });
                }
            }
        });
    }
},
  //购买车票: 下方购买车票的点击按钮
  onBuyTicketButtonTap: function onBuyTicketButtonTap() {
    if(this.data.isRegular==0){
      wx.showToast({
        title: '未开通班次',
        icon: "none"
    });
    }else{
      wx.navigateTo({
        url: "/pages/buy-ticket/buy-ticket?lineId=" + this.data.busLineId + "&regularDate=" +this.data.regular.date+"&regularId=" +this.data.regular.id+ "&isBifa="+this.data.regular.bifa
    });
    }
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
     // 调用接口
//      qqmapsdk.search({
//       keyword: '酒店',
//       success: function (res) {
//           console.log(res);
//       },
//       fail: function (res) {
//           console.log(res);
//       },
//   complete: function (res) {
//       console.log(res);
//   }
// });


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})